﻿using LivestreamE_Commerce.Dto.Tree;
using LivestreamE_Commerce.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LivestreamE_Commerce.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MyRoleController : ControllerBase
    {
        LivestreamE_CommerceDbContext db;
        public MyRoleController(LivestreamE_CommerceDbContext _db) 
        {
            db = _db;
        }
        [HttpGet,Route("RoleTree")]
        public async Task<IActionResult> RoleTree()
        {
            var list = await Task.Run(() => RoleTrees(""));
            return Ok(new { list = list, state = true });
        }
        private List<RoleTreeDto> RoleTrees(string FenId)
        {
            var list = db.RoleModel.ToList();
            var newlist = list.Where(x => Convert.ToString(x.FatherId).Equals( FenId)).ToList();
            List<RoleTreeDto> result = new List<RoleTreeDto>();
            newlist.ForEach(p =>
            {
                RoleTreeDto t = new RoleTreeDto();
                t.Id = p.Id.ToString();
                t.Label = p.RoleName;
                t.Url = p.Url;
                t.Children = RoleTrees(p.Id.ToString());
                result.Add(t);
            });
            return result;
        }

    }
}
